package com.jp.knowledge.my.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.google.gson.JsonObject;
import com.iflytek.cloud.SpeechError;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.activity.LoginActivity;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.dialog.SearchPopuWindow;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.logic.PersonLogic;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.adapter.SearchListAdapter;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.my.model.SearchResultModel;
import com.jp.knowledge.my.resources.OrganizeJoinRes;
import com.jp.knowledge.my.util.MyUtil;
import com.jp.knowledge.util.ResultSubscriber;
import com.jp.knowledge.util.VoiceInputUtils;
import com.jp.knowledge.view.RecycleViewDiver;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * 内容列表检索
 */
public class SearchListActivity extends SlidingActivity implements ResultSubscriber.OnResultListener, RecycleVAdapter.OnItemClickListener, View.OnClickListener {

    private static final int CREATE_COMPANY_CODE = 0x01;

    @ViewInject(R.id.can_content_view)
    protected RecyclerView searchList;
    @ViewInject(R.id.search_rly_edt)
    protected RelativeLayout searchEditBg;
    @ViewInject(R.id.search_list_edt_search)
    protected EditText searchEdit;
    @ViewInject(R.id.search_list_iv_clear)
    protected ImageView searchClear;
    @ViewInject(R.id.search_list_iv_voice)
    protected ImageView voiceInput;
    @ViewInject(R.id.refresh)
    protected CanRefreshLayout refreshLayout;
    @ViewInject(R.id.search_bg)
    protected LinearLayout background;
    @ViewInject(R.id.search_bg_tv)
    protected TextView backgroundTV;
    @ViewInject(R.id.search_list_btn_create)
    protected TextView createBn;

    @ViewInject(R.id.create_company_center_btn)
    protected TextView createCenterBn;
    @ViewInject(R.id.create_company_bottom_lly)
    protected LinearLayout createBottomLayout;

    protected int requestCode;
    protected SearchListAdapter searchListAdapter;
    protected List<SearchResultModel> searchResults;
    private UserData userData;

    protected int page;
    protected Intent intent;
    private boolean isSearching;

    private CommDialog joinRemindDialog;
    private CommDialog setRealNameDialog;
    private SearchPopuWindow searchPopuWindow;

    @Override
    protected int getResourceId() {
        return R.layout.activity_search_list;
    }

    @Override
    protected void init() {
        this.page = 0;
        this.isSearching = false;
        this.userData = application.getUserData();
        this.intent = getIntent();
        this.requestCode = intent.getIntExtra(OrganizeJoinRes.REQUEST_CODE, -1);
//        ((TextView)this.findViewById(R.id.search_list_text_create))
//                .setText(OrganizeJoinRes.SEARCH_REMIND_CREATE[this.requestCode]);
        ((TextView)this.findViewById(R.id.search_list_text_create))
                .setText(R.string.join_others_organize_remind_create);
        setCreateButton(3);
        searchList.setHasFixedSize(true);
        searchList.setLayoutManager(new LinearLayoutManager(this));
        searchList.addItemDecoration(new RecycleViewDiver(this, LinearLayout.HORIZONTAL));
        searchList.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                MyUtil.closeKeyword(SearchListActivity.this, searchEdit);
            }
        });

        searchResults = new ArrayList<>();
        searchListAdapter = new SearchListAdapter(SearchListActivity.this, new ArrayList<SearchResultModel>());
        searchListAdapter.addItemClickListener(this);
        searchList.setAdapter(searchListAdapter);
        initTitle(intent.getStringExtra(OrganizeJoinRes.TITLE));

        refreshLayout.setRefreshEnabled(false);
        refreshLayout.setLoadMoreEnabled(false);
        refreshLayout.setOnLoadMoreListener(new CanRefreshLayout.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                doSearch(searchEdit.getText().toString(), ++SearchListActivity.this.page);
            }
        });
        searchClear.setVisibility(View.GONE);
        searchClear.setOnClickListener(this);
        voiceInput.setOnClickListener(this);
        leftIcon.setOnClickListener(this);
        createBn.setOnClickListener(this);
        createCenterBn.setOnClickListener(this);
        searchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                MyUtil.closeKeyword(SearchListActivity.this, searchEdit);
                if (actionId == EditorInfo.IME_ACTION_SEARCH && searchEdit.getText().toString().trim().length() > 0) {
                    loading.show();
                    isSearching = true;
                    searchPopuWindow.dismiss();
                    SearchListActivity.this.page = 0;
                    doSearch(searchEdit.getText().toString(), ++SearchListActivity.this.page);
                }
                return true;
            }
        });
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {};
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {};
            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() == 0 && searchClear.getVisibility() == View.VISIBLE)
                    searchClear.setVisibility(View.GONE);
                else if(s.length() > 0 && searchClear.getVisibility() == View.GONE)
                    searchClear.setVisibility(View.VISIBLE);
//                SearchListActivity.this.page = 0;
//                doSearch(searchEdit.getText().toString(), ++SearchListActivity.this.page);
                if(s.length() == 0){
                    searchPopuWindow.dismiss();
                    searchPopuWindow.clearList();
                } else if(!isSearching){
                    searchPopuWindow.searchKeyWord(s.toString());
                }
            }
        });
        showRemindBg(false);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                MyUtil.startKeyword(SearchListActivity.this, searchEdit);
            }
        }, 300);
        initDialog();
    }

    private void initTitle(String title) {
        topName.setText(title);
        topDesc.setVisibility(View.GONE);
        leftIcon.setImageResource(R.mipmap.arrow_white_left);
        rightIcon.setVisibility(View.GONE);
    }

    private void initDialog(){
        joinRemindDialog = new CommDialog(this);
        joinRemindDialog.setLeft("取消");
        joinRemindDialog.setRight("加入");
        joinRemindDialog.setTag(-1);
        joinRemindDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int selectPosition = (int)joinRemindDialog.getTag();
                if(selectPosition >= 0)
                    joinOrganization(selectPosition);
                joinRemindDialog.dismiss();
            }
        });

        setRealNameDialog = new CommDialog(this);
        setRealNameDialog.setEditHint("请填入真实姓名");
        setRealNameDialog.setShowWithKeyword(true);
        setRealNameDialog.setRightClickDismiss(false);
        setRealNameDialog.setRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = setRealNameDialog.getEditText();
                if(text.trim().length() == 0) {
                    ToasUtil.toast(mContext, "请输入有效的真实姓名");
                } else {
                    setRealName(text);
                    setRealNameDialog.dismiss();
                }
            }
        });

        searchPopuWindow = new SearchPopuWindow(this);
        searchPopuWindow.setSearchRemindCallback(new SearchPopuWindow.SearchRemindCallback() {
            @Override
            public void showRemindPopWindow() {
                if(searchPopuWindow.isShowing())
                    return;
                searchPopuWindow.dismiss();
                searchPopuWindow.showAsDropDown(searchEditBg);
            }
        });
        searchPopuWindow.setOnItemLisertern(new SearchPopuWindow.OnSearchItemListener() {
            @Override
            public void onItemListener(String key) {
                MyUtil.closeKeyword(SearchListActivity.this, searchEdit);
                isSearching = true;
                searchEdit.setText(key);
                searchEdit.setSelection(key.length());
                loading.show();
                searchPopuWindow.dismiss();
                SearchListActivity.this.page = 0;
                doSearch(searchEdit.getText().toString(), ++SearchListActivity.this.page);
            }
        });
    }

    private void showJoinDialog(int position){
        joinRemindDialog.setTag(position);
        joinRemindDialog.setContent("是否加入“" + searchResults.get(position).getName() + "”？");
        joinRemindDialog.setRight("加入");
        if(TextUtils.isEmpty(userData.getUpdateName()))
            setRealNameDialog.show();
        else
            joinRemindDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || null == data)
            return;
        if(requestCode == CREATE_COMPANY_CODE) {
            setResult(data.getStringExtra(OrganizeJoinRes.RESPONSE_RESULT),
                    data.getStringExtra(OrganizeJoinRes.RESPONSE_RESULT));
            finishSelf();
        }
    }

    @Override
    public void itemSelect(int position) {
//        setResult(searchResults.get(position).getName(), searchResults.get(position).getId());
//        finishSelf();
        if(!application.isLogin()){
            startActivity(new Intent(this, LoginActivity.class));
            return;
        } else if(userData.getIsVip() != 1
                && userData.getCompanyList() != null
                && userData.getCompanyList().size() > 1
                && searchResults.get(position).getType() != 2){
            joinRemindDialog.setTag(-1);
            joinRemindDialog.setContent("请升级为VIP后才能加入多家组织");
            joinRemindDialog.setRight("确定");
            joinRemindDialog.show();
            return;
        }

        setResult(searchResults.get(position).getName(), searchResults.get(position).getId());
        intent.putExtra(OrganizeJoinRes.REQUEST_CODE, searchResults.get(position).getType()-1);
        if(searchResults.get(position).getType() - 1 == OrganizeJoinRes.SCHOOL_INDEX) {
            intent.putExtra(OrganizeJoinRes.TITLE, "选择院系");
        } else {
            intent.putExtra(OrganizeJoinRes.TITLE, "选择部门");
//            joinOrganization(position);
            showJoinDialog(position);
            return;
        }
        intent.putExtra(OrganizeJoinRes.COMPANY_NAME, searchResults.get(position).getName());
        intent.setClass(this, DepartmentActivity.class);
        MyUtil.closeKeyword(SearchListActivity.this, searchEdit);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(intent);
            }
        }, 300);
    }

    private void setResult(String companyName, String id){
        intent.putExtra(OrganizeJoinRes.RESPONSE_RESULT, companyName);
        intent.putExtra(OrganizeJoinRes.ID, id);
        setResult(RESULT_OK, intent);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {
        isSearching = false;
    }
    @Override
    public void onError(int requestType) {
        loading.cancel();
        if(isSearching) {
            ToasUtil.toast(this, "抱歉，数据加载失败，请稍后重试");
        }
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(requestType != this.requestCode)
            return;
        if(this.page <= 1)
            this.searchResults.clear();
        List<SearchResultModel> results = data.getList(SearchResultModel.class);
        searchResults.addAll(results);
        if(this.requestCode == OrganizeJoinRes.SCHOOL_INDEX){
        } else if(searchResults.size() == 0) {
            showRemindBg(true);
            if(searchEdit.getText().toString().length() == 0)
                setCreateButton(0);
            else
                setCreateButton(2);
        } else{
            showRemindBg(false);
            setCreateButton(1);
        }
        searchListAdapter.updateAdapter(searchResults);
        refreshLayout.loadMoreComplete();
//        cancleLoading();
        isSearching = false;
        loading.cancel();
    }

    @Override
    protected void onStart() {
        super.onStart();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                MyUtil.startKeyword(SearchListActivity.this, searchEdit);
            }
        }, 300);
    }

    private void doSearch(String keyWord, int page){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("keyword", keyWord);
        param.addProperty("page", page);
        if(requestCode != -1)
            param.addProperty("type", requestCode+1);
        HttpHelper.getInstance(this).searchOrganize(param, requestCode, this);
    }

    private void showRemindBg(boolean isShow){
        this.background.setVisibility(isShow ? View.VISIBLE : View.GONE);
        this.refreshLayout.setVisibility(isShow ? View.GONE : View.VISIBLE);
    }

    protected void finishSelf() {
        MyUtil.closeKeyword(SearchListActivity.this, searchEdit);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 300);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_list_iv_clear:
                SearchListActivity.this.searchEdit.setText("");
                break;
            case R.id.search_list_iv_voice:
                openVoiceInput();
                break;
            case R.id.icon_left:
                SearchListActivity.this.finishSelf();
                break;
            case R.id.create_company_center_btn:
            case R.id.search_list_btn_create:
                MyUtil.closeKeyword(SearchListActivity.this, searchEdit);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        Intent intent = new Intent(SearchListActivity.this, CompanyCreateActivity.class);
//                        intent.putExtra("type", requestCode+1);
//                        intent.putExtra("type", 1);
//                        startActivityForResult(intent, CREATE_COMPANY_CODE);
                        startActivity(new Intent(SearchListActivity.this, OrganizeJoinActivity.class));
                    }
                }, 300);
                break;
            default:
                return;
        }
    }

    private static final int REQUEST_RECORD_AUDIO_CODE = 0x01;
    /* 打开语音输入 */
    private void openVoiceInput(){
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                && (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED)){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_AUDIO_CODE);
        } else {
            searchEdit.setText("");
            VoiceInputUtils.getInstance(mContext).startInput(new VoiceInputUtils.VoiceInputCallback() {
                @Override
                public void onResult(String result) {
                    if(result.trim().length() > 0) {
                        searchEdit.setText(result);
                        searchEdit.setSelection(result.length());

                        loading.show();
                        isSearching = true;
                        SearchListActivity.this.page = 0;
                        doSearch(searchEdit.getText().toString(), ++SearchListActivity.this.page);
                    }
                }
                @Override
                public void onChanged(String str) {
                    searchEdit.setText(searchEdit.getText().toString()+str);
                    searchEdit.setSelection(searchEdit.getText().length());
                }
                @Override
                public void onError(SpeechError speechError) {}
            });
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO_CODE && grantResults.length > 0){
            if(grantResults[0] != PackageManager.PERMISSION_GRANTED)
                ToasUtil.toast(mContext, "抱歉，你没有权限访问打开麦克风，请到设置中开启麦克风权限后重试");
            else
                openVoiceInput();
        }
    }

    protected void setCreateButton(int showType){
        if(showType == 1){
            createCenterBn.setVisibility(View.GONE);
            createBottomLayout.setVisibility(View.VISIBLE);
        } else if(showType == 2){
//            this.backgroundTV.setText(OrganizeJoinRes.SEARCH_BG_REMIND_CREATE[this.requestCode]);
            this.backgroundTV.setText(R.string.join_others_organize_bg_remind_create);
            createCenterBn.setVisibility(View.VISIBLE);
            createBottomLayout.setVisibility(View.GONE);
        } else{
//            this.backgroundTV.setText(OrganizeJoinRes.SEARCH_BG_REMIND[this.requestCode]);
            this.backgroundTV.setText(R.string.join_others_organize_bg_remind);
            createCenterBn.setVisibility(View.GONE);
            createBottomLayout.setVisibility(View.GONE);
        }
    }

    private void setRealName(String realName){
        JsonObject param = new JsonObject();
        param.addProperty("username", realName);
        HttpHelper.getInstance(mContext).updateUserInfo(param, 0x01, new ResultSubscriber.OnResultListener() {
            @Override
            public void onStart(int requestType) {
                loading.show();
            }
            @Override
            public void onCompleted(int requestType) {}
            @Override
            public void onError(int requestType) {
                loading.cancel();
            }
            @Override
            public void onNext(IModel data, int requestType) {
                if(data.getErrcode() != 0){
                    ToasUtil.toast(mContext, data.getMessage());
                    onError(requestType);
                } else{
                    joinOrganization((int) joinRemindDialog.getTag());
                }
            }
        });
    }

    private void joinOrganization(final int index){
        JsonObject param = new JsonObject();
        param.addProperty("token", HttpHelper.token);
        param.addProperty("id", searchResults.get(index).getId());
        param.addProperty("type", searchResults.get(index).getType());
        HttpHelper.getInstance(this).commitJoinOrganize(param, searchResults.get(index).getType(), new ResultSubscriber.OnResultListener(){
            @Override
            public void onStart(int requestType) {}
            @Override
            public void onCompleted(int requestType) {
                loading.cancel();
            }
            @Override
            public void onError(int requestType) {
                loading.cancel();
//                ToasUtil.toast(SearchListActivity.this, "抱歉，组织加入失败，请稍后重试");
            }
            @Override
            public void onNext(IModel data, int requestType) {
                if(data.getErrcode() != 0){
                    ToasUtil.toast(mContext, data.getMessage());
                    onError(requestType);
                    return;
                }

                List<OrganizaModel> organizaModels = data.getList(OrganizaModel.class);
                if(organizaModels != null && organizaModels.size() > 0) {
                    List<OrganizaModel> userOrganizes = application.getUserData().getCompanyList();
                    application.getUserData().setCompanyList(organizaModels);

                    for(OrganizaModel organizaModel : organizaModels){
                        if(!userOrganizes.contains(organizaModel)){
                            LocalBroadcastManager.getInstance(mContext)
                                    .sendBroadcast(new Intent(LocalBroadCast.COMPANY_JOIN)
                                            .putExtra("joinCompany", organizaModel)
                                            .putExtra("index", organizaModels.indexOf(organizaModel)));
                            break;
                        }
                    }
                }
//                OrganizaModel organizaModel = data.getEntity(OrganizaModel.class);
//                organizaModel.setCompanyType(searchResults.get(index).getType());
//                LocalBroadcastManager.getInstance(context)
//                        .sendBroadcast(new Intent(LocalBroadCast.COMPANY_JOIN)
//                                .putExtra("joinCompany", organizaModel));

//                updataUserData();
//                ToasUtil.toast(SearchListActivity.this, "组织加入成功");
                intent.setClass(SearchListActivity.this, OrganizeActivity.class);
                startActivity(intent);
                SearchListActivity.this.finishSelf();
            }
        });
    }

    private void updataUserData(){
        if(application.getUserData() == null
                || application.getUserData().getCompanyId() == null
                || application.getUserData().getCompanyId().trim().length() == 0){
            new PersonLogic(this).getUserData();
        }
    }

    @Override
    public void onBackPressed() {
        if(searchPopuWindow.isShowing())
            searchPopuWindow.dismiss();
        else
            super.onBackPressed();
    }
}
